from urllib.parse import urlsplit

from django.core.paginator import Paginator
from django.db.models import Q
from django.forms import model_to_dict
from django.http import JsonResponse, HttpResponse

from Wallpaper.models import Category, Wallpaper, LiveWallpaper, LiveCategory


# Create your views here.
def index(request):
    return HttpResponse("index")


def get_all_category(request):
    c = Category.objects.all()
    categories = [model_to_dict(i) for i in c]
    data = {
        "status": "success",
        "categories": categories,
    }
    return JsonResponse(data, status=200, json_dumps_params={"ensure_ascii": False})


def get_all_live_category(request):
    c = LiveCategory.objects.all()
    categories = [model_to_dict(i) for i in c]
    data = {
        "status": "success",
        "categories": categories,
    }
    return JsonResponse(data, status=200, json_dumps_params={"ensure_ascii": False})


def get_random_wallpaper(request):
    count = request.GET.get("count", 50)
    wallpaper_list = Wallpaper.objects.all().order_by('?')
    wallpapers = [model_to_dict(i) for i in wallpaper_list[:count]]
    http = urlsplit(request.build_absolute_uri(None)).scheme
    host = f"{http}://{request.META['HTTP_HOST']}"
    for i in wallpapers:
        if i.get('url').startswith("/"):
            i['url'] = host + i.get('url')
    data = {
        "errno": 0,
        "msg": "success",
        "data": {
            "list": wallpapers,
        }
    }
    return JsonResponse(data, status=200, json_dumps_params={"ensure_ascii": False})


def get_wallpaper(request):
    category_name: str = request.GET.get("category")  # 分类
    pageno: int = int(request.GET.get("page", 1))  # 分页
    count: int = int(request.GET.get("count", 9))  # 每页数量
    order: str = request.GET.get("order")  # 按时间排序，升序或降序
    orientation: str = request.GET.get("orientation")  # 壁纸方向
    wallpaper_list = Wallpaper.objects.all()
    if category_name:
        category = Category.objects.get(name=category_name)
        wallpaper_list = wallpaper_list.filter(category=category)
    if order == "TimeASC":
        wallpaper_list = wallpaper_list.order_by('create_time')
    elif order == "random":
        wallpaper_list = wallpaper_list.order_by('?')
    else:
        wallpaper_list = wallpaper_list.order_by('-create_time')
    if orientation == "horizontal":
        wallpaper_list = wallpaper_list.filter(orientation=Wallpaper.HORIZONTAL)
    paginator = Paginator(wallpaper_list, count)
    total_count = paginator.count
    total_page = paginator.num_pages
    page_obj = paginator.page(pageno) if pageno <= total_page else []
    wallpapers = [model_to_dict(i) for i in page_obj]
    http = urlsplit(request.build_absolute_uri(None)).scheme
    host = f"{http}://{request.META['HTTP_HOST']}"
    for i in wallpapers:
        if i.get('url').startswith("/"):
            i['url'] = host + i.get('url')
    data = {
        "errno": 0,
        "msg": "success",
        "data": {
            "total_count": total_count,
            "total_page": total_page,
            "pageno": pageno,
            "count": count if pageno <= total_page else 0,
            "list": wallpapers,
        }
    }
    return JsonResponse(data, status=200, json_dumps_params={"ensure_ascii": False})


def get_live_wallpaper(request):
    category_name: str = request.GET.get("category")  # 分类
    pageno: int = int(request.GET.get("page", 1))  # 分页
    count: int = int(request.GET.get("count", 9))  # 每页数量
    order: str = request.GET.get("order")  # 按时间排序，升序或降序
    orientation: str = request.GET.get("orientation")  # 壁纸方向
    wallpaper_list = LiveWallpaper.objects.all()
    if category_name:
        category = LiveCategory.objects.get(name=category_name)
        wallpaper_list = wallpaper_list.filter(category=category)
    if order == "TimeASC":
        wallpaper_list = wallpaper_list.order_by('create_time')
    elif order == "random":
        wallpaper_list = wallpaper_list.order_by('?')
    else:
        wallpaper_list = wallpaper_list.order_by('-create_time')
    if orientation == "horizontal":
        wallpaper_list = wallpaper_list.filter(orientation=Wallpaper.HORIZONTAL)
    paginator = Paginator(wallpaper_list, count)
    total_count = paginator.count
    total_page = paginator.num_pages
    page_obj = paginator.page(pageno) if pageno <= total_page else []
    wallpapers = [model_to_dict(i) for i in page_obj]
    http = urlsplit(request.build_absolute_uri(None)).scheme
    host = f"{http}://{request.META['HTTP_HOST']}"
    for i in wallpapers:
        if i.get('url').startswith("/"):
            i['url'] = host + i.get('url')
    data = {
        "errno": 0,
        "msg": "success",
        "data": {
            "total_count": total_count,
            "total_page": total_page,
            "pageno": pageno,
            "count": count if pageno <= total_page else 0,
            "list": wallpapers,
        }
    }
    return JsonResponse(data, status=200, json_dumps_params={"ensure_ascii": False})


def search(request):
    keyword: str = request.GET.get("keyword")
    pageno: int = int(request.GET.get("page", 1))
    count: int = int(request.GET.get("count", 9))
    order: str = request.GET.get("order")
    wallpaper_list = Wallpaper.objects.all().filter(Q(tag__contains=keyword))
    if order == "TimeASC":
        wallpaper_list = wallpaper_list.order_by('create_time')
    elif order == "random":
        wallpaper_list = wallpaper_list.order_by('?')
    else:
        wallpaper_list = wallpaper_list.order_by('-create_time')
    paginator = Paginator(wallpaper_list, count)
    total_count = paginator.count
    total_page = paginator.num_pages
    page_obj = paginator.page(pageno) if pageno <= total_page else []
    wallpapers = [model_to_dict(i) for i in page_obj]
    http = urlsplit(request.build_absolute_uri(None)).scheme
    host = f"{http}://{request.META['HTTP_HOST']}"
    for i in wallpapers:
        if i.get('url').startswith("/"):
            i['url'] = host + i.get('url')
    data = {
        "errno": 0,
        "msg": "success",
        "data": {
            "total_count": total_count,
            "total_page": total_page,
            "pageno": pageno,
            "count": count if pageno <= total_page else 0,
            "list": wallpapers,
        }
    }
    return JsonResponse(data, status=200, json_dumps_params={"ensure_ascii": False})


def get_data(request):
    # key = request.GET.get("keyword")
    # print(key)
    # BirdWallpaperSpider(category=key).get_live_wallpaper()
    # spider = NetBiAnWallpaperSpider()
    # for c in spider.keys:
    #     spider.main(c)
    # spider = BiZhi4KWallpaperSpider()
    # for key in spider.keys:
    #     spider.horizontal_wallpaper(key)
    # spider = AiBiZhiWallpaperSpider()
    # for i in spider.categories:
    #     spider.main(i)
    # set_datetime.main()
    # set_img_info()
    data = {
        "status": "success",
        "count": None,
    }
    return JsonResponse(data, status=200, json_dumps_params={"ensure_ascii": False})
